package com.moonlight.demo.custom;

import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

public class CustomEncoder extends ProtocolEncoderAdapter {
	public Charset charset;
	
	public CustomEncoder(Charset charset) {
		this.charset = charset;
	}

	@Override
	public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
		// TODO Auto-generated method stub
		CustomPackage customPackage = (CustomPackage) message;
		int len = customPackage.getLen();
		byte type = customPackage.getType();
		String content = customPackage.getContent();
		IoBuffer buffer = IoBuffer.allocate(len);
		buffer.putInt(len);
		buffer.put(type);
		buffer.put(content.getBytes(charset));
		buffer.flip();
		out.write(buffer);
	}

}
